import { hasValue } from '../../utils/util'
import { fetchPlayerList, getPlayerPrice, checkTurnCode, insTurn } from '../../api/index';

function getUniquePlayerNames(playerList: any[], statsOne: string, statsTwo: string): { text: string; value: string }[] {
  // 使用 Set 来存储 statsOne 的唯一值
  const uniqueNames = new Set<string>();
  playerList.forEach((player) => {
    uniqueNames.add(player[statsTwo]);
  });

  // 使用 Map 来存储 statsOne 和对应的 statsTwo
  const nameScoreMap = new Map<string, string>();
  uniqueNames.forEach((name) => {
    const playersWithSameName = playerList.filter((p) => p[statsTwo] === name);
    if (playersWithSameName.length > 0) {
      // 选择第一个匹配的 player 的 statsTwo 的值
      const firstMatch = playersWithSameName[0];
      // 确保 statsTwo 的值总是存在
      const score = firstMatch[statsOne] || 'default_value'; // 替换 'default_value' 为实际的默认值
      nameScoreMap.set(name, score);
    }
  });

  // 遍历 Map，确保每个唯一的 statsOne 值只返回一个有效的 statsTwo 值
  const result = [];
  nameScoreMap.forEach((score, name) => {
    if (score !== 'default_value') { // 如果 score 不是默认值，则添加到结果中
      result.push({ text: score, value: name });
    }
  });

  // 返回结果
  return result;
}
Component({
  data: {
    topImage: 'https://bd.yiquhz.com/bg/ff3081.jpg',
    playerList: [],
    userNameList: [],
    GameList: [],
    RoleList: [],
    formPlayer: {
      userName: '',// gameUser
      gameName: '',// turnOld
      totalPrice: '',
      turnPrice: '',// turnPrice
      turnGame: '',
      turnPartition: '',// turnNew
      turnRole: ''
    },
    turnInfo: [],
    turnGameP: [],//游戏名称
    turnGames: [],
    turnRoles: [],
    turnCode: '',// turnCode
    securityCode: '',
    show: false,
    openId: ''
  },
  methods: {
    onLoad: function () {
      this.setData({
        openId: wx.getStorageSync('openId')
      })
      if (hasValue(this.data.openId)) {
        this.getPlayerList(this.data.openId)
      } else {
        wx.reLaunch({ url: "/pages/usercenter/index" });
      }
    },
    //获取用户游戏信息
    getPlayerList: async function (openId: string) {
      try {
        const playerList = await fetchPlayerList(openId, true);
        if (playerList == null) {
          wx.showToast({
            title: '暂无转区信息',
          })
          return
        }
        // 使用 map 函数将 playerList 中的属性转换为所需格式
        const userIdList = getUniquePlayerNames(playerList, "playerName", "playerName");
        this.setData({
          userNameList: userIdList,
          playerList: playerList,
          "formPlayer.openId": playerList[0].openId
        })
      } catch (err) {
        wx.redirectTo({ url: "/pages/empty/empty" });
      }
    },
    // 游戏账号
    onUserChange(e: any) {
       // 筛选出特定游戏的玩家
       const filteredPlayers = this.data.playerList.filter(player => player.playerName === e.detail);
       const GameList = getUniquePlayerNames(filteredPlayers, "gamePartition", "partitionId");
       this.setData({
        "formPlayer.userName": e.detail,
         GameList: GameList,
         "formPlayer.gameName": '',
         "formPlayer.totalPrice":'',
         "formPlayer.turnGame":'',
         turnGameP:[],
         "formPlayer.turnPartition":'',
         turnGames:[],
         "formPlayer.turnPrice":'',
         turnCode:''
       })
    },
    //游戏分区
    onGameChange(e: any) {
      if (hasValue(this.data.formPlayer.userName)) {
        //计算当前账号在这个区中的充值金额， 转区信息
        this.setData({
          "formPlayer.gameName": e.detail,
          "formPlayer.totalPrice":'',
         "formPlayer.turnGame":'',
         turnGameP:[],
         "formPlayer.turnPartition":'',
         turnGames:[],
         "formPlayer.turnPrice":'',
         turnCode:''
        })
        //获取转区金额
        this.getPlayerPrice(this.data.formPlayer);
        //获取可转区信息
        const filteredItems = this.data.playerList.filter(item => item.partitionId !== e.detail
          && item.playerName === this.data.formPlayer.userName);
        if(filteredItems.length === 0){
          wx.showToast({ title: '请先前往新区注册，游戏账号需一致!', icon: 'none' });
          this.setData({
            turnGameP: [],
            turnInfo: []
          })
          return
        }
        //游戏名称
        const GamePList = getUniquePlayerNames(filteredItems, "gameName", "gameName");
        this.setData({
          turnGameP: GamePList,
          turnInfo: filteredItems
        })
      } else {
        wx.showModal({
          showCancel: false,
          title: '提示',
          content: '游戏账号为空，请按顺序选择！',
          success(res) {
            if (res.confirm) {
            }
          }
        })
        this.setData({
          "formPlayer.gameName": ''
        })
      }
    },
    onTurnGamePChange(e: any) {
      //根据选择的游戏名称，筛选这个游戏下的分区
      const filteredItems = this.data.turnInfo.filter(item => item.gameName == e.detail);
      // 使用 map 函数将 playerList 中的属性转换为所需格式
      const GameList = getUniquePlayerNames(filteredItems, "gamePartition", "partitionId");
      this.setData({
        turnGames:GameList,
        "formPlayer.turnGame": e.detail,
        turnCode: ''
      })
    },
    onTurnGameChange(e: any) {
      const turnCode = Math.floor((Math.random() * 100000) + 1).toString().padStart(5, '0')
      this.checkTurnCode(turnCode)
      this.setData({
        "formPlayer.turnPartition": e.detail,
      })
    },
    //排除转区码重复
    checkTurnCode: async function (turnCode: string) {
      try {
        const checkResult = await checkTurnCode(turnCode);
        if (checkResult) {
          this.setData({ turnCode: turnCode })
        } else {
          const turnCode = Math.floor((Math.random() * 100000) + 1).toString().padStart(5, '0')
          this.checkTurnCode(turnCode)
        }
      } catch (err) {
        console.log(err)
        wx.redirectTo({ url: "/pages/empty/empty" });
      }
    },
    //获取转区金额
    getPlayerPrice: async function (formPlayer: object) {
      try {
        const playerPrice = await getPlayerPrice(formPlayer);
        if (playerPrice.count == 0) {
          this.setData({
            "formPlayer.turnPrice": 0,
            "formPlayer.totalPrice": 0
          })
          return
        }
        if (playerPrice.code == 0) {
          this.setData({
            "formPlayer.turnPrice": playerPrice.obj.topupTotal / 100,
            "formPlayer.totalPrice": playerPrice.obj.topupPrice
          })
          return
        } else {
          wx.showToast({
            title: playerPrice.message,
            icon: 'none',
            duration: 2000
          });
        }
      } catch (err) {
        wx.redirectTo({ url: "/pages/empty/empty" });
      }
    },
    showPopup() {
      if (this.data.turnCode.length > 0) {
        //新增转区审核
        this.toInsTurn(this.data.formPlayer, this.data.turnCode)
      } else {
        wx.showToast({
          title: "请先完善信息，再继续",
          icon: 'none',
          duration: 2000
        });
      }
    },
    //获取转区金额
    toInsTurn: async function (turn: object, turnCode: string) {
      try {
        const turnIns = await insTurn(turn, turnCode);
        if (turnIns.code == 0) {
          if(turnIns.count == 0){
            this.setData({ show: true });
            wx.showToast({
              title: turnIns.message,
              icon: 'none',
              duration: 2000
            });
          }else{
            this.setData({ turnCode: turnIns.message, show: true });
          }
        } else {
          wx.showToast({
            title: turnIns.message,
            icon: 'none',
            duration: 2000
          });
        }
      } catch (err) {
        wx.redirectTo({ url: "/pages/empty/empty" });
      }
    },
    onClose() {
      this.setData({
        show: false,
        "formPlayer.turnGame": '',
        "formPlayer.turnPartition": '',
        "formPlayer.turnRole": '',
        turnCode: '',
        securityCode: ''
      });
    },
    copyInfo() {
      wx.setClipboardData({
        data: this.data.turnCode,
        success() {
          wx.showToast({
            title: '复制成功',
          })
        }
      })
    },
  }
})